package com.gm.wholesale.module.order.ui;

import android.content.Context;
import android.graphics.Color;
import android.text.TextUtils;
import android.util.ArrayMap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.gm.commonlib.base.baseAdapter.CommonAdapter;
import com.gm.commonlib.base.baseAdapter.ViewHolder;
import com.gm.commonlib.base.baseView.IBaseView;
import com.gm.commonlib.base.baseui.baseFragment.BaseFragment;
import com.gm.commonlib.module.evenbus.EventMessage;
import com.gm.commonlib.util.numberUtils.NumberUtils;
import com.gm.commonlib.util.permission.PermissionUtil;
import com.gm.commonlib.util.permission.interfaces.IPermissionCallback;
import com.gm.commonlib.util.stringUtils.StringUtils;
import com.gm.commonlib.util.timeUtils.DateTimeUtils;
import com.gm.commonlib.util.viewUtils.RepeatClickUtils;
import com.gm.commonlib.util.viewUtils.ViewUtil;
import com.gm.commonlib.views.BadgeView;
import com.gm.commonlib.views.dialog.DialogUtil;
import com.gm.commonlib.views.dialog.InputDialog;
import com.gm.commonlib.views.popupwindow.Popupwindow;
import com.gm.commonlib.views.popupwindow.Popupwindow2;
import com.gm.commonlib.views.superview.SuperTextView;
import com.gm.commonlib.views.toast.ToastUtil;
import com.gm.wholesale.GMApplication;
import com.gm.wholesale.R;
import com.gm.wholesale.cacheData.CacheData;
import com.gm.wholesale.module.evenbus.EvenBusUtil;
import com.gm.wholesale.module.evenbus.EventBusType;
import com.gm.wholesale.db.DatabaseHelper;
import com.gm.wholesale.db.order.DBOrderUtil;
import com.gm.wholesale.db.order.bean.DBOrderBean;
import com.gm.wholesale.db.order.bean.DBOrderContentBean;
import com.gm.wholesale.module.config.ConfigData;
import com.gm.wholesale.module.custom.ChoiceCustomData;
import com.gm.wholesale.module.custom.bean.CustomBean;
import com.gm.wholesale.module.good.bean.GoodBean;
import com.gm.wholesale.module.main.ui.MainActivity;
import com.gm.wholesale.module.order.bean.OrderDetailBean;
import com.gm.wholesale.module.order.presenter.CreateOrderPresenter;
import com.gm.wholesale.module.order.presenter.MainOrderFgPresenter;
import com.gm.wholesale.module.order.view.ChoiceGoodTagView;
import com.gm.wholesale.util.AppUtil;
import com.gm.wholesale.util.CloneUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

public class MainOrderFragment extends BaseFragment implements View.OnClickListener {

    private TextView mChoiceCustomTv;
    private TextView saveOrderToLocalTv;
    private TextView showSaveOrdersTv;
    private TextView cancelOrderTv;

    private ListView orderListView;
    private TextView totalPriceTv;
    private TextView arrearsTv;
    private SuperTextView submitOrderTv;
    private ImageView voiceImage;
    private MainActivity mMainActivity;
    private TextView showNtTv;
    private BadgeView mBadgeView;

    private List<GoodBean> mGoodBeans = new ArrayList<>();

    private CommonAdapter mAdapter;

    @Override
    protected void onCreateContentBody(ViewGroup parent) {
        super.onCreateContentBody(parent);
        //这个fragment 默认在 xml 配置了。默认就会创建，这里加个处理
        if (!ConfigData.getConfigData().hasCreateOrderPermission()) { //没有开单权限，进入订单管理界面
            return;
        }
        View view = LayoutInflater.from(context).inflate(R.layout.fragment_order, parent);
        initView(view);
        showSaveOrderSize();
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        mMainActivity = (MainActivity) context;

    }

    @Override
    public void onReceiveEvent(EventMessage event) {
        super.onReceiveEvent(event);
        if (event == null) return;
        //todo 显示默认散客信息
        int evenType = event.getCode();
        if (evenType == EventBusType.SHOW_DEFAULT_CUSTORM.getType()) {
            showCustomView((CustomBean) event.getData());
        }
        //清空订单数据
        else if (evenType == EventBusType.CLERAN_ORDER.getType()) {
            clearData();
        }
        if (event.getCode() == EventBusType.UPDATE_ORDER.getType()) {
            OrderDetailBean orderDetailBean = (OrderDetailBean) event.getData();
            OrderDetailBean.CustomerInfoDTO customerInfo = orderDetailBean.getCustomerInfo();
            CustomBean customBean = new CustomBean();
            customBean.setName(customerInfo.getCustomerName());
            customBean.setId(customerInfo.getCustomerId());
            ChoiceCustomData.newInstance().setCustomBean(customBean);
            List<GoodBean> goodBeans = new ArrayList<>();
            List<OrderDetailBean.OrderDetailsDTO> orderDetails = orderDetailBean.getOrderDetails();
            if (orderDetails != null) {

                for (OrderDetailBean.OrderDetailsDTO orderDetailsDTO : orderDetails) {
                    GoodBean goodBean = new GoodBean();
                    goodBean.setId(orderDetailsDTO.getSkuId());
                    goodBean.setName(orderDetailsDTO.getSkuName());
                    goodBean.setGoodNum(Double.parseDouble(orderDetailsDTO.getQuantity()));
                    goodBean.setPrice(Double.parseDouble(orderDetailsDTO.getUnitPrice()));
                    goodBean.setUnitName(orderDetailsDTO.getOrderingUnitName());
                    goodBean.setTempId(AppUtil.getUUid());
                    goodBean.setOrderLineId(orderDetailsDTO.getOrderLineId());
                    goodBean.setUnits(orderDetailsDTO.getUnits());
                    double totalPrice = 0;
                    if (goodBean.getGoodNum() < 0 || goodBean.getPrice() < 0) {
                        totalPrice = 0;
                    } else {
                        totalPrice = NumberUtils.mul(goodBean.getGoodNum(), goodBean.getPrice());
                    }
                    goodBean.setTotalPrice(totalPrice);
                    goodBeans.add(goodBean);
                }
            }
            OrderDetailBean.OrderInfoDTO orderInfoDTO = orderDetailBean.getOrderInfo();
            showUpdateView(goodBeans, orderInfoDTO.getOrderId(), orderInfoDTO.getVersion());
            if (mMainActivity != null) {
                mMainActivity.showMainUI();
            }

        }
    }

    //todo 获取展示 挂单数量
    public void showSaveOrderSize() {
        if (mMainActivity != null) {
            int orderSize = DBOrderUtil.getOrderSize(mMainActivity.getGMApplication().getDatabaseHelper());
            remindMsg(mBadgeView, orderSize);
        }
    }

    public void showCustomView(CustomBean customBean) {
        if (customBean != null) {
            mChoiceCustomTv.setText(customBean.getName());
        }

    }

    private void initView(View view) {
        mChoiceCustomTv = view.findViewById(R.id.choiceUserTv);
        saveOrderToLocalTv = view.findViewById(R.id.saveOrderToLocalTv);
        showSaveOrdersTv = view.findViewById(R.id.showSaveOrdersTv);
        showNtTv = view.findViewById(R.id.showNtTv);
        mBadgeView = new BadgeView(context, showNtTv);
        cancelOrderTv = view.findViewById(R.id.cancelOrderTv);
        orderListView = view.findViewById(R.id.orderListView);
        totalPriceTv = view.findViewById(R.id.totalPriceTv);
        arrearsTv = view.findViewById(R.id.arrearsTv);
        submitOrderTv = view.findViewById(R.id.submitOrderTv);
        voiceImage = view.findViewById(R.id.voiceImage);
        cancelOrderTv.setOnClickListener(this);
        arrearsTv.setOnClickListener(this);
        mChoiceCustomTv.setOnClickListener(this);
        saveOrderToLocalTv.setOnClickListener(this);
        showSaveOrdersTv.setOnClickListener(this);
        submitOrderTv.setOnClickListener(this);
        voiceImage.setOnClickListener(this);

        handleVoiceImage();
    }

    //todo 有语音录入权限 才显示按钮
    private void handleVoiceImage() {
        voiceImage.setVisibility(View.GONE);
        if (ConfigData.getConfigData() != null) {
            if (ConfigData.getConfigData().hasVoicePermission()) {
                voiceImage.setVisibility(View.VISIBLE);
            }
        }


    }

    private void remindMsg(BadgeView badgeView, int size) {
        badgeView.setBadgePosition(BadgeView.POSITION_TOP_RIGHT);// 显示的位置.右上角,BadgeView.POSITION_BOTTOM_LEFT,下左，还有其他几个属性
        badgeView.setTextColor(Color.WHITE); // 文本颜色
        badgeView.setBadgeBackgroundColor(Color.RED); // 提醒信息的背景颜色，自己设置
        badgeView.setTextSize(12); // 文本大小
        badgeView.setBadgeMargin(0, 0);
        badgeView.show();// 只有显示
        if (size > 99) {
            badgeView.setText("99+"); // 需要显示的提醒类容
        } else {
            badgeView.setText(size + ""); // 需要显示的提醒类容
        }
        if (size <= 0) {
            badgeView.hide();
        }


    }

    private void checkAutoPermission() {
        PermissionUtil.applyAudioPermission(getActivity(), new IPermissionCallback() {
            @Override
            public void onPermissionResult(boolean result, Set<String> dataSet) {
                if (result) {
                    mMainActivity.startVoice();
                } else {
                    ToastUtil.showToast("请打开录音权限");
                }
            }
        });
    }


    @Override
    public void onClick(View view) {
        if (RepeatClickUtils.check()) {
            return;
        }
        int viewId = view.getId();
        if (viewId == R.id.voiceImage) {
            checkAutoPermission();
            return;
        }
        if (viewId == R.id.choiceUserTv) {
            mMainActivity.showChoiceCustom(view);
            return;
        }
        if (viewId == R.id.cancelOrderTv) {
            if (mGoodBeans == null || mGoodBeans.isEmpty()) {
                return;
            }
            DialogUtil.show(getActivity(), "是否整单取消?", (dialogInterface, i) -> clearData());
            return;
        }
        if (viewId == R.id.saveOrderToLocalTv) {
            saveCurrentOrderToDB();
        }
        if (viewId == R.id.showSaveOrdersTv) {
            GMApplication application = (GMApplication) getActivity().getApplication();
            List<DBOrderBean> dbOrderBeans = DBOrderUtil.getDBOrderBean(application.getDatabaseHelper());
            if (dbOrderBeans == null || dbOrderBeans.isEmpty()) {
                return;
            }
            View popListView = LayoutInflater.from(context).inflate(R.layout.view_pop_order_size, null);
            ListView listView = popListView.findViewById(com.gm.commonlib.R.id.listView);
            String defaultName = "挂单";
            listView.setAdapter(new CommonAdapter<>(context, dbOrderBeans, R.layout.list_pop_order_item) {
                @Override
                public void convert(ViewHolder view, DBOrderBean data) {
                    int pos = view.getPosition() + 1;
                    //兼容老数据做一个判断。没有客户名字显示挂单xx，有客户名字显示客户名字（开始没保存客户名字）
                    //后面需求要求 新加
                    if (TextUtils.isEmpty(data.getOther1())) {
                        view.setText(R.id.nameTv, defaultName + pos);
                    } else {
                        view.setText(R.id.nameTv, data.getOther1());
                    }

                    view.setText(R.id.createTimeTv, DateTimeUtils.formatDateTime(data.getTime(), DateTimeUtils.HMD));
                    view.getConvertView().setOnClickListener(view1 -> {
                        if (mGoodBeans != null && !mGoodBeans.isEmpty()) {
                            DialogUtil.show(getActivity(), "正在开单，取单后当前订单将挂起，是否取单？",
                                    (dialogInterface, i) -> {
                                        saveCurrentOrderToDB();
                                        getOrderByDB(data);
                                        Popupwindow.hiddenPop();
                                    });
                        } else {
                            getOrderByDB(data);
                        }

                    });
                }
            });
            Popupwindow2.showPopView(getActivity(), showSaveOrdersTv, popListView);

        }
        if (viewId == R.id.submitOrderTv) {
            String errorMsg = checkOrderData();
            if (!StringUtils.isEmpty(errorMsg)) {
                ToastUtil.showToast(errorMsg);
                return;
            }
            //修改订单
            if (orderId > 0) {
                updateOrder();
            } else { //创建新订单
                subMitOrder();
            }
            return;
        }

    }

    //todo 提交订单
    private void subMitOrder() {
        CreateOrderPresenter.subMitOrder(context, mGoodBeans, ()
                -> EvenBusUtil.clearnHomeOrder()
        );
    }

    private void updateOrder() {
        CreateOrderPresenter.updateOrder(context, orderId, orderVersion, mGoodBeans,
                () -> EvenBusUtil.clearnHomeOrder()
        );
    }

    private String checkOrderData() {
        if (mGoodBeans == null || mGoodBeans.isEmpty()) {
            return "请先创建订单";
        }
        return "";
    }


    // todo 保存当前录单到本地数据库
    private void saveCurrentOrderToDB() {
        if (mGoodBeans.isEmpty()) {
            return;
        }
        GMApplication application = (GMApplication) getActivity().getApplication();
        List<DBOrderContentBean> orderContentBeans = new ArrayList<>();
        for (GoodBean goodBean : mGoodBeans) {
            orderContentBeans.add(goodBean.toDBOrderBean());
        }
        DBOrderUtil.saveOrder(application.getDatabaseHelper(), orderContentBeans);
        showSaveOrderSize();
        clearData();
    }

    private void getOrderByDB(DBOrderBean data) {
        Popupwindow2.hiddenPop();
        DatabaseHelper databaseHelper = mMainActivity.getGMApplication().getDatabaseHelper();
        List<DBOrderContentBean> orderContentBeans = DBOrderUtil.getDBOrderDetailByOrderId(databaseHelper, data.getOrderId());
        if (orderContentBeans == null) {
            return;
        }
        mGoodBeans.clear();
        for (DBOrderContentBean orderContentBean : orderContentBeans) {
            mGoodBeans.add(orderContentBean.toGoodBean());
        }
        if (orderContentBeans != null && !orderContentBeans.isEmpty()) {
            updateCustom(orderContentBeans.get(0));
        }
        updateView();
        DBOrderUtil.deleteOrder(databaseHelper, data.getId());
        showSaveOrderSize();
    }

    private void updateCustom(DBOrderContentBean orderContentBean) {
        if (orderContentBean != null) {
            CustomBean customBean = orderContentBean.getCustomBean();
            if (customBean != null) {
                ChoiceCustomData.newInstance().setCustomBean(customBean);
                mMainActivity.updateCustom(customBean);
            }
        }
    }


    public void clearData() {
        orderId = 0;
        orderVersion = 0;
        if (mAdapter != null && mGoodBeans != null) {
            mGoodBeans.clear();
            mAdapter.notifyDataSetChanged();
        }
        if (ChoiceCustomData.newInstance().mSanKeCustomBean != null) {
            showCustomView(ChoiceCustomData.newInstance().mSanKeCustomBean);
            ChoiceCustomData.newInstance().setCustomBean(ChoiceCustomData.newInstance().mSanKeCustomBean);
        } else {
            mMainActivity.getDefaultCustom();
        }
        resetTotalPrice();
    }

    private void resetTotalPrice() {
        totalPriceTv.setText("￥0.00");
    }

    private long orderId;
    private long orderVersion;

    public void showUpdateView(List<GoodBean> goodBeans, long orderId, long orderVersion) {
        this.orderId = orderId;
        this.orderVersion = orderVersion;
        mGoodBeans.clear();
        mGoodBeans.addAll(goodBeans);
        // todo 更新客户信息
        showCustomView(ChoiceCustomData.newInstance().getCustomBean());
        updateView();
    }

    public void addGoodBean(GoodBean goodBean) {
        double totalPrice = NumberUtils.mul(goodBean.getGoodNum(), goodBean.getPrice());
        if (totalPrice < 0) {
            totalPrice = 0;
        }
        goodBean.setTotalPrice(totalPrice);
        if (TextUtils.isEmpty(goodBean.getTempId())) {
            goodBean.setTempId(AppUtil.getUUid());
            mGoodBeans.add(goodBean);
        } else {
            boolean mIsExit = false;
            for (GoodBean goodBean1 : mGoodBeans) {
                if (goodBean1.getTempId().equals(goodBean.getTempId())) {
                    mIsExit = true;
                    goodBean1.setIsVoiceCreate(goodBean.isIsVoiceCreate());
                    goodBean1.setGoodNum(goodBean.getGoodNum());
                    goodBean1.setTemporaryGood(goodBean.isTemporaryGood());
                    goodBean1.setId(goodBean.getId());
                    goodBean1.setUnitName(goodBean.getUnitName());
                    goodBean1.setPrice(goodBean.getPrice());
                    goodBean1.setUnitId(goodBean.getUnitId());
                    goodBean1.setTotalPrice(totalPrice);
                    goodBean1.setName(goodBean.getName());
                    goodBean1.setSearchGoods(goodBean.getSearchGoods());
                    goodBean1.setAddWeightBeans(goodBean.getAddWeightBeans());
                    break;
                }
            }
            if (!mIsExit) {
                goodBean.setTempId(AppUtil.getUUid());
                mGoodBeans.add(goodBean);
            }
        }

        updateView();
    }

    private void showTotalPrice() {
        double total = 0;
        for (GoodBean goodBean : mGoodBeans) {
            if (goodBean.getPrice() >= 0) {
                total = NumberUtils.addDouble(total, goodBean.getTotalPrice());
            }
        }
        if (total <= 0) {
            resetTotalPrice();
        } else {
            setTotalPriceTv(total);
        }

    }

    private void setTotalPriceTv(Double data) {
        totalPriceTv.setText("￥" + NumberUtils.getMoneyString(data));
    }

    public void updateView() {
        showTotalPrice();
        if (mAdapter != null) {
            mAdapter.notifyDataSetChanged();
            return;
        }
        mAdapter = new CommonAdapter<>(context, mGoodBeans, R.layout.list_order_item) {
            @Override
            public void convert(ViewHolder view, GoodBean good) {
                TextView goodNameTv = view.getView(R.id.goodNameTv);
                if (good.getId() <= 0) {
                    ViewUtil.setCompoundDrawables(getActivity(), goodNameTv, ViewUtil.POS_LEFT, R.drawable.new_good);
                } else {
                    ViewUtil.cleanDrawable(goodNameTv);
                }
                view.setText(R.id.goodNameTv, good.getName());
                view.setText(R.id.goodNumTv, NumberUtils.getMoneyString(good.getGoodNum()));
                view.setText(R.id.goodUnitTv, good.getUnitName());
                view.setText(R.id.goodPriceTv, NumberUtils.getMoneyString(good.getPrice()));
                view.setText(R.id.totalPriceTv, NumberUtils.getMoneyString(good.getTotalPrice()));
                view.getView(R.id.deleteOrderImg).setOnClickListener(view1 -> {

                    DialogUtil.show(getActivity(), "是否删除该商品?", (dialogInterface, i) -> {
                        mGoodBeans.remove(good);
                        //todo 如果删除完了，则订单id置空。不然添加商品 会走修改订单逻辑
                        if (mGoodBeans.isEmpty()) {
                            orderId = 0;
                        }
                        showTotalPrice();
                        notifyDataSetChanged();
                    });

                });
                // todo 新商品才能修改
                if (good.getId() <= 0) {
                    view.getView(R.id.goodNameTv).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            if (good.getId() <= 0) { //todo 新商品才能修改
                                updateGoodName(good);
                            }

                        }
                    });
                }

                view.getConvertView().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        good.setIsUpdateView(true);
                        GoodBean newGood = CloneUtil.clone(good);
                        if (newGood == null) {
                            newGood = good;
                        }
                        //商品id小于0 说明是新商品（则是语音录入创建的商品）
                        if (good.getId() <= 0) {
                            mMainActivity.updateGoodForVoiceView(newGood);
                        } else {
                            mMainActivity.showCreateOrderView(newGood);
                        }
                    }
                });
            }

        };
        orderListView.setAdapter(mAdapter);
    }

    private void updateGood(GoodBean goodBean, GoodBean newGood) {
        goodBean.setUnitName(newGood.getUnitName());
        goodBean.setName(newGood.getName());
        if (CacheData.getIsAutoInputPrice()) {
            goodBean.setPrice(newGood.getPriceByJin());
        }
        goodBean.setId(newGood.getId());
        addGoodBean(goodBean);
    }


    //修改商品名称
    private void updateGoodName(GoodBean goodBean) {

        if (goodBean != null) {
            InputDialog inputDialog1 = DialogUtil.showInputDialog(getContent(), "修改商品名称", goodBean.getName(), (inputData, inputDialog) -> {
                if (TextUtils.isEmpty(inputData)) {
                    ToastUtil.showToast("请输入商品名称");
                    return;
                }
                inputDialog.dismiss();
                ArrayMap<String, Object> queryData = new ArrayMap<>();
                queryData.put("name", inputData);
                MainOrderFgPresenter.searchGoodByName((IBaseView) getActivity(), queryData, new MainOrderFgPresenter.OnSearchGoodFinishListener() {
                    @Override
                    public void onSearchGood(List<GoodBean> goodBeans) {

                        if (goodBeans != null && !goodBeans.isEmpty()) {
                            updateGood(goodBean, goodBeans.get(0));
                        } else {
                            //新商品
                            goodBean.setName(inputData);
                            goodBean.setId(0);
                            mAdapter.notifyDataSetChanged();
                        }
                    }
                });

            });
            ChoiceGoodTagView choiceGoodTagView = new ChoiceGoodTagView(getActivity());
            MainOrderFgPresenter.searchGoodByKey(null, goodBean.getName(), new MainOrderFgPresenter.OnSearchGoodFinishListener() {
                @Override
                public void onSearchGood(List<GoodBean> goodBeans) {
                    if (goodBeans != null && !goodBeans.isEmpty()) {
                        if (goodBeans.size() == 1 && goodBean.getName().equals(goodBeans.get(0).getName())
                                && goodBean.getUnitName().equals(goodBeans.get(0).getUnitName())) {
                            return;
                        }
                        List<GoodBean> newGoods = new ArrayList<>();
                        for (GoodBean searchGood : goodBeans) {
                            if (!goodBean.getName().equals(searchGood.getName())
                                    || !goodBean.getUnitName().equals(searchGood.getUnitName())) {
                                newGoods.add(searchGood);
                            }
                        }
                        if (newGoods.isEmpty()) {
                            return;
                        }
                        choiceGoodTagView.showView(newGoods, new ChoiceGoodTagView.OnTagGoodClickListener() {
                            @Override
                            public void onTagGoodClick(GoodBean newGood) {
                                inputDialog1.dismiss();
                                updateGood(goodBean, newGood);
                            }
                        });
                        inputDialog1.setContentView(choiceGoodTagView);
                    }
                }
            });

        }


    }


}

